'use strict';

const Service = require('egg').Service;

class CommentService extends Service {
  async getCommentList(essayId, userId) {
    const list = await this.app.mysql.query(`SELECT id,  content, user_id,
    (SELECT username FROM user WHERE a.user_id = user.id) AS username,
    (SELECT position FROM user WHERE a.user_id = user.id) AS position,
    (SELECT avatar_url FROM user WHERE a.user_id = user.id) AS avatar_url,
    (SELECT is_like FROM comment_like WHERE a.id = comment_like.comment_id AND user_id = ${userId}) AS is_like,
    (SELECT SUM(is_like) FROM comment_like WHERE a.id = comment_like.comment_id) AS like_count,
    (SELECT COUNT(content) FROM comment WHERE a.id = comment.reply_comment_id) AS comment_count
    FROM comment a
    WHERE essay_id = ${essayId} AND reply_comment_id = 0`);

    for (let i = 0; i < list.length; i++) {
      const replyId = list[i].id;
      const replyList = await this.app.mysql
        .query(`SELECT id,  content, user_id, reply_comment_id,
        (SELECT username FROM user WHERE a.user_id = user.id) AS username,
        (SELECT position FROM user WHERE a.user_id = user.id) AS position,
        (SELECT avatar_url FROM user WHERE a.user_id = user.id) AS avatar_url,
        (SELECT is_like FROM comment_like WHERE a.id = comment_like.comment_id AND user_id = ${userId}) AS is_like,
        (SELECT SUM(is_like) FROM comment_like WHERE a.id = comment_like.comment_id) AS like_count,
        (SELECT COUNT(content) FROM comment WHERE a.id = comment.reply_comment_id) AS comment_count
        FROM comment a
        WHERE essay_id = ${essayId} AND reply_comment_id = ${replyId}`);
      list[i].reply_comment = replyList;
    }
    return { list };
  }

  async addComment(data) {
    const res = await this.app.mysql.insert('comment', data);
    const id = res.insertId;
    return { id };
  }

  async deleteComment(commentId, userId) {
    const result = await this.app.mysql.delete('comment', {
      id: commentId,
      user_id: userId,
    });
    const deleteSuccess = result.affectedRows === 1;
    return { deleteSuccess };
  }

  async likeComment(commentId, userId) {
    const result = await this.app.mysql.insert('comment_like', {
      comment_id: commentId,
      user_id: userId,
      is_like: 1,
    });
    const insertSuccess = result.affectedRows === 1;
    return { insertSuccess };
  }

  async dislikeComment(commentId, userId) {
    const result = await this.app.mysql.delete('comment_like', {
      comment_id: commentId,
      user_id: userId,
    });
    const deleteSuccess = result.affectedRows === 1;
    return { deleteSuccess };
  }
}

module.exports = CommentService;
